package chapter1_3_wait_notify;

/**
 * 当前线程调用共享变量的wa it（） 方法后只会释放当前共享变量上
 * 的锁，如果当前线程还持有其他共享变量的锁，则这些锁是不会被释放的 ==> 死锁
 * @author huayuhao
 * @date 2020/12/15 15:46
 */
public class WaitTest {

    private static volatile Object resourceA = new Object();
    private static volatile Object resourceB = new Object();

    public static void main(String[] args) throws InterruptedException {

        System.out.println("演示当前线程调用共享变量wait方法只会释放当前共享变量上的锁--> 从而产生死锁");

        Thread threadA = new Thread(()->{
            try{
                synchronized (resourceA){
                    System.out.println("threadA 获得了 resourceA 锁");
                    synchronized (resourceB){
                        System.out.println("threadA 获得了 resourceB 锁");
                        System.out.println("threadA 释放了 resourceA 锁");
                        resourceA.wait();
                    }
                }
            }catch (InterruptedException e){
                e.printStackTrace();
            }
        });
        Thread threadB = new Thread(()->{
            try{
                Thread.sleep(1000);
               synchronized (resourceA){
                   System.out.println("threadB 获得了 resourceA 锁");
                   System.out.println("threadB 尝试去获取 resourceB 锁");
                   synchronized (resourceB){
                       System.out.println("threadB 获得了 resourceB 锁");
                       System.out.println("threadB 释放了 resourceA 锁");
                       resourceA.wait();
                   }
               }
            }
            catch (InterruptedException ex){
                ex.printStackTrace();
            }
        });
        threadA.start();
        threadB.start();

        threadA.join();
        threadB.join();
        System.out.println("main over ! ");
    }
}
